import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/home/news_item_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/utils/local_read_history.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';

import 'package:ball_lion/widgets/base/wqs_text.dart';

enum PinStyle { none, top, normal }

class NewsItemCell extends StatelessWidget {
  final NewsItemEntity e;
  final int? classId;
  final bool inHome;
  final int? imgStyle;
  final void Function()? afterRoute;
  final bool bottomDivider;
  final bool isSubscribe;
  final String? id;
  final PinStyle style;
  final Function()? onTap;

  const NewsItemCell(this.e,
      {super.key,
      this.classId,
      this.inHome = true,
      this.imgStyle,
      this.afterRoute,
      this.bottomDivider = true,
      this.isSubscribe = false,
      this.style = PinStyle.none,
      this.id,
      this.onTap});

  @override
  Widget build(BuildContext context) {
    return _cell();
  }

  _cell() {
    // final c = _cell3(e);
    late Widget c;
    final style = imgStyle ?? e.imgStyle ?? 1;
    if (style == 1) {
      c = _cell1(e);
    } else if (style == 2) {
      c = _cell2(e);
    } else {
      c = _cell3(e);
    }

    return GestureDetector(
      onTap: () {
        if (isSubscribe) {
          Get.toNamed(Routes.subscribeArticle, arguments: e.id);
          return;
        }
        int? classId = this.classId;
        Utils.onEvent("home_article",
            params: {"article_id": e.id, "channel": id});
        if (e.imgStyle == 4) {
          Get.toNamed(Routes.homeVideoNews,
              arguments: e.id,
              parameters: {'classId': "$classId"})?.then((value) {
            afterRoute?.call();
          });
        } else {
          // Get.to(NewsView(data: e));
          Get.toNamed(Routes.homenews,
                  arguments: e.id,
                  parameters: {'classId': "$classId", "id": id ?? ""},
                  preventDuplicates: false)
              ?.then((value) {
            afterRoute?.call();
          });
        }
      },
      behavior: HitTestBehavior.opaque,
      child: Container(
        clipBehavior: Clip.hardEdge,
        decoration: BoxDecoration(
            color: Colours.white, borderRadius: BorderRadius.circular(0)),
        child: c.paddingOnly(left: 16, right: 16, top: 12),
      ),
    );
  }

  Widget _buildTopView() {
    if (style == PinStyle.top) {
      return Container(
          alignment: Alignment.centerLeft,
          padding: EdgeInsets.only(bottom: 8),
          child: Image.asset(
            Utils.getImgPath("pin_news_top.png"),
            width: 64,
            height: 14,
          ));
    } else if (style == PinStyle.normal) {
      return Container(
          alignment: Alignment.centerLeft,
          padding: EdgeInsets.only(bottom: 8),
          child: Image.asset(
            Utils.getImgPath("pin_news_normal.png"),
            width: 55,
            height: 15,
          ));
    } else {
      return const SizedBox.shrink(); // or any other widget if needed
    }
  }

  Widget _title(NewsItemEntity e) {
    final readed =
        e.isRead == 1 ? true : LocalReadHistory.hasReadedNews("${e.id}");
    final color = readed ? Colours.N7 : Colours.N9;
    return Text.rich(
      TextSpan(children: [
        // if ((e.top ?? 0) >= 1 && inHome)
        //   WidgetSpan(
        //       alignment: PlaceholderAlignment.middle,
        //       child: Image.asset(Utils.getImgPath("pin_top.png"), width: 16)),
        TextSpan(
          text: e.title ?? "",
          style: TextStyle(
            fontSize: 17,
            color: color,
            height: 1.2,
          ),
        ).formHighLight()
      ]),
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
      textAlign: TextAlign.left,
    );
  }

  Widget _bottomRow(NewsItemEntity e) {
    final l = [
      e.publisherName?.trim(),
      e.pv?.trim(),
      if (inHome) e.publishTime?.trim()
    ];
    l.removeWhere((element) => element?.isEmpty ?? true);
    return DefaultTextStyle(
      maxLines: 1,
      style: const TextStyle(fontSize: 11, color: Colours.N7),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.baseline,
        textBaseline: TextBaseline.alphabetic,
        children: [
          QsText(e.publisherName?.trim() ?? ''),
          if (inHome) QsText(' · ${e.publishTime?.trim() ?? ''}'),
          if (e.commentNum.hasValue) QsText(" · 评论${e.commentNum}"),
          QsText(' · ${e.pv?.trim() ?? ''}'),
        ],
      ),
    );
  }

  //无图
  _cell1(NewsItemEntity e) {
    return Column(
      children: [
        _buildTopView(),
        SizedBox(
          child: Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [_title(e), _bottomRow(e)],
                ),
              ),
            ],
          ),
        ),
        const Divider(color: Colours.N3, height: 0.5)
            .marginOnly(top: 10), // 在列表项底部添加分割线
      ],
    );
  }

  //右图
  _cell2(NewsItemEntity e) {
    return Column(children: [
      _buildTopView(),
      Container(
        height: 72,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Expanded(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.max,
              children: [Expanded(child: _title(e)), _bottomRow(e)],
            )),
            Container(
                decoration:
                    BoxDecoration(borderRadius: BorderRadius.circular(4)),
                clipBehavior: Clip.hardEdge,
                margin: const EdgeInsets.only(left: 12),
                width: 114,
                height: 71,
                child: CachedNetworkImage(
                  imageUrl: e.imgs ?? "",
                  fit: BoxFit.cover,
                  errorWidget: (context, url, error) =>
                      Container(color: Colors.white),
                  placeholder: ((context, url) =>
                      Container(color: Colors.white)),
                )),
          ],
        ),
      ),
      const Divider(color: Colours.N3, height: 0.5).marginOnly(top: 10)
    ]); // 在列表项底部添加分割线]);
  }

  //大图
  _cell3(NewsItemEntity e) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildTopView(),
        _title(e),
        Stack(
          alignment: Alignment.center,
          children: [
            Container(
              decoration:
                  BoxDecoration(borderRadius: BorderRadius.circular(10)),
              clipBehavior: Clip.hardEdge,
              child: AspectRatio(
                  aspectRatio: 343 / 146,
                  child: CachedNetworkImage(
                      imageUrl: e.imgs ?? "",
                      fit: BoxFit.cover,
                      errorWidget: (context, url, error) =>
                          Container(color: Colors.white),
                      placeholder: ((context, url) =>
                          Container(color: Colors.white)))),
            ),
            if (e.type == 3)
              Image.asset(Utils.getImgPath('home_video_play.png'), width: 50)
          ],
        ),
        const SizedBox(height: 10),
        _bottomRow(e),
        const Divider(color: Colours.N3, height: 0.5).marginOnly(top: 10),
      ],
    );
  }
}
